import { UserOutlined } from "@ant-design/icons";
import { Bubble, Sender, useXAgent, useXChat } from "@ant-design/x";
import { Flex, type GetProp } from "antd";
import React, { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { pushRecord,updateChat } from "@/store/modules/chat";
import { fetchChat } from "@/api/chat";
import  parsePack  from "./parsePack";
import markdownit from 'markdown-it';
const md = markdownit({ html: true, breaks: true });
// 自定义渲染规则
md.renderer.rules.paragraph_open = (tokens, idx) => {
  return '<p class="no-margin">';
};
import "./index.css";

const sleep = () => new Promise((resolve) => setTimeout(resolve, 1000));

const roles: GetProp<typeof Bubble.List, "roles"> = {
  ai: {
    placement: "start",
    avatar: { icon: <UserOutlined />, style: { background: "#fde3cf" } },
    typing: false,
    style: {
      maxWidth: 600,
    },
  },
  local: {
    placement: "end",
    avatar: { icon: <UserOutlined />, style: { background: "#87d068" } },
  },
};

let mockSuccess = false;

const App = () => {
  const [content, setContent] = React.useState("");
  const [content2, setContent2] = useState<any[]>([]);
  const [key, setKey] = useState(0);
  const dispatch = useDispatch();
  const scrollContainerRef = useRef(null);
  let chatRecord = useSelector((state: any) => state.chat.chatRecord);
  let chatId = useSelector((state: any) => state.chat.conversation_id);
  const [agent] = useXAgent({
    request: async ({ message }, { onSuccess, onError }) => {
      await sleep();

      mockSuccess = !mockSuccess;

      if (mockSuccess) {
        onSuccess(`Mock success return. You said: ${message}`);
      }

      onError(new Error("Mock request failed"));
    },
  });

  // Chat messages
  // const { onRequest, messages } = useXChat({
  //   agent,
  //   requestPlaceholder: "Waiting...",
  //   requestFallback: "Mock failed return. Please try again later.",
  // });
  const container = scrollContainerRef.current;

 
  useEffect(() => {
    console.log("scrollscrollscrollscrollscrollscroll")
    const srollBottom = () => {
      if (container&&chatRecord.length>0) {
        container.scrollTop = container.scrollHeight;
        console.log(container.scrollHeight);
      }
    };
    srollBottom();
  }, [container?.scrollHeight, key,chatRecord]);
  useEffect(() => {
    dispatch(updateChat(content2))
   
  }, [content2]); 
  async function request(nextContent:any) {
    setContent2([])
    dispatch(
      pushRecord({
        conversationId: "10a112da19e34ee9bc5349e99e16ba53",
        messageId: "10a112da19e34ee9bc5349e99e16ba53",
        dateTime: "",
        error: false,
        isReply: false,
        like_or_dislike: 0,
        collect_state: 0,
        additional_state: 0,
        kbName: 0,
        content: nextContent,
        showToolBar: false,
        thinking: false,
      })
    );
    dispatch(
      pushRecord({
        conversationId: "10a112da19e34ee9bc5349e99e16ba53",
        messageId: "10a112da19e34ee9bc5349e99e16ba53",
        dateTime: "",
        error: false,
        isReply: true,
        like_or_dislike: 0,
        collect_state: 0,
        additional_state: 0,
        kbName: 0,
        content: "",
        showToolBar: false,
        thinking: false,
      })
    );
    await fetchChat.create(
      {
        messages: [{ content: nextContent,chatId: chatId }],
        stream: true,
      },
      {
        onSuccess: async (messages) => {
          // console.error("onSuccess", messages);
        },
        onError: (error) => {
          console.error("onError", error);
        },
        onUpdate: async (msg) => {
          const chunk: any[] = parsePack(msg);
          const text=chunk.map((item)=>item.answer)
          setContent2((pre) => [...pre, ...text]);
          // dispatch(updateChat(content2))
        },
      },
      new TransformStream<string, string>({
        transform(chunk, controller) {
          controller.enqueue(chunk);
        },
      })
    );
  }
  return (
    <div className="chat">
      <div className="chatBox" ref={scrollContainerRef}>
        <Bubble.List
          key={key}
          roles={roles}
          items={chatRecord.map((item: any) => ({
            key: item.conversation_id,
            role: !item.isReply ? "local" : "ai",
            content: <div dangerouslySetInnerHTML={{ __html: md.render(String(Array.isArray(item.content) ? item.content.join('') : item.content || '')) }} />,
          }))}
        />
      </div>

      <div className="chatInput">
        <Sender
          loading={agent.isRequesting()}
          value={content}
          onChange={setContent}
          onSubmit={(nextContent:string) => {
            setKey(key + 1);
            // onRequest(nextContent);
            setContent("");
            // pushRecord(nextContent)
            // request(nextContent)
            request(nextContent);
          }}
        />
      </div>
    </div>
  );
};

export default App;
